﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace NeedForSmash
{
    class World
    {
        private Game m_game;

        static private float m_gravity = 0.981f;
        
        private List<Element> m_elementList;
        public List<Element> ElementList
        {
            get
            {
                return m_elementList;
            }
        }

        private List<Character> m_characterList;
        public List<Character> CharacterList
        {
            get
            {
                return m_characterList;
            }
        }

        public World(Game game)
        {
            m_game = game;
            m_elementList = new List<Element>();
            m_characterList = new List<Character>();
        }

        public void Update(GameTime gameTime)
        {
            float elapsedTime = (float)gameTime.ElapsedGameTime.Milliseconds / 400.0f;

            foreach (Element e in ElementList)
            {
                if (e.IsStatic == false)
                {
                    e.m_velocity.Y -= m_gravity * elapsedTime;
                    e.Move(new Vector3(0, e.m_velocity.Y * elapsedTime, 0));
                    if (CheckCollision(e))
                    {
                        e.Move(new Vector3(0, -e.m_velocity.Y * elapsedTime, 0));
                        e.StopMove();
                    }
                }
            }

            foreach (Character c in CharacterList)
            {
                c.Velocity -= new Vector3(0, m_gravity * elapsedTime, 0);
                c.Move(new Vector3(0, c.Velocity.Y * elapsedTime, 0));
                if (CheckCollision(c))
                {
                    c.Backup();
                    c.StopMove();
                }
            }
        }

        private bool CheckCollision(Element e)
        {
            foreach (Element ee in ElementList)
            {
                if (e != ee)
                {
                    if (e.BoundingBox.Intersects(ee.BoundingBox))
                        return true;
                }
            }
            return false;
        }

        private bool CheckCollision(Character c)
        {
            foreach (Element e in ElementList)
            {
                if (c.BoundingBox.Intersects(e.BoundingBox))
                    return true;
            }
            return false;
        }
    }
}
